﻿using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;

namespace QiNiuStorage
{
    /// <summary>
    /// NuGet引用： Qiniu(8.3.1)
    /// 七牛云存储官网：  https://www.qiniu.com/products/kodo
    /// 七牛云存储空间管理：  https://portal.qiniu.com/kodo/bucket   !!!!! 切记：设置为：公开空间
    /// c#参考官网文档：  https://developer.qiniu.com/kodo/1237/csharp   /  https://developer.qiniu.com/kodo/1500/csharp-sdk-v7p0
    /// </summary>
    public class QiNiuHelper
    {
        //string filePath        UploadFile(filePath)
        //byte[] data            UploadData(data)
        //FileStream fs          UploadStream(fs)
        //MemoryStream           UploadStream(fs)

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云上传普通文件
        /// </summary>
        public async static Task<QiNiuResult> QiNiuUploadFile(string ak, string sk, string bucket,string filePath, string baseUrl,Stream st)
        {
            // 设置上传策略
            PutPolicy putPolicy = new QiNiuHelper().SetPutPolicy();

            // 生成上传token
            Mac mac = new Mac(ak, sk);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            // 设置上传区域
            Config config = new QiNiuHelper().SetConfigZone();

            // 表单上传
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadStream(st, bucket, token, null);
            Console.WriteLine("返回结果： " + result.ToString());

            var imgUrl = baseUrl + bucket;
            return new QiNiuResult
            {
                Url = imgUrl,
                Success=true,       
            };
        }
        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云删除文件
        /// </summary>
        public async static Task<QiNiuResult> QiNiuDeleteFile(string ak,string sk,string saveKey,string bucket)
        {
            ////保存到七牛云上的文件目录
            ////string saveKey = "images/44.jpg";
            //var saveKey = "Images/demo/ren3.jpg";

            //设置上传区域
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_North;//ZONE_CN_North
            Mac mac = new Mac(ak, sk);

            BucketManager bucketManager = new BucketManager(mac, config);
            HttpResult deleteRet = bucketManager.Delete(bucket, saveKey);
            Console.WriteLine($"删除文件结果：Bucket={bucket}, SaveKey={saveKey}, Code={deleteRet.Code}, Text={deleteRet.Text}");
            
            if (deleteRet.Code == (int)HttpCode.OK)
            {
                return new QiNiuResult
                {
                    Url = "",
                    Success = true,
                };
            }
            else
            {
                return new QiNiuResult
                {
                    Url = "",
                    Success = false,
                };
            }
        }
        /// <summary>
        /// 设置上传策略
        /// </summary>
        /// <returns></returns>
        public PutPolicy SetPutPolicy()
        {
            PutPolicy putPolicy = new PutPolicy();

            // 设置要上传的目标空间
            putPolicy.Scope = "ghr666";

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略有效期(对应于生成的凭证的有效期，单位:秒)
            putPolicy.SetExpires(3600);

            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            return putPolicy;
        }
        
 

        /// <summary>
        /// 设置上传区域
        /// </summary>
        /// <returns></returns> 
        public Config SetConfigZone()
        {
            Config config = new Config();

            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_North;

            // 设置 http 或者 https 上传
            config.UseHttps = true;

            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            return config;
        }
        /// <summary>
        /// 七牛云操作结果
        /// </summary>
        public class QiNiuResult
        {
            /// <summary>
            /// 文件URL
            /// </summary>
            public string? Url { get; set; }

            public bool? Success { get; set; }

        }
    }
}
